#coding=utf-8
import smtplib,os,time
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
import datetime

from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr

import poplib




import imaplib
import email


yesterday=datetime.datetime.now()+datetime.timedelta(days=1, hours=-0.5)
yesterday=yesterday.strftime("%Y%m%d")

def parseHeader(message):
    """ 解析邮件首部 """
    subject = message.get('subject')
    h = email.Header.Header(subject)
    dh = email.Header.decode_header(h)
    # subject = unicode(dh[0][0], dh[0][1]).encode('gb2312')
    subject = unicode(dh[0][0], dh[0][1]).encode('utf8')
    # 主题
    print subject,11111111111111
    print '</br>'
    # 发件人
    print 'From:', email.utils.parseaddr(message.get('from'))[1]
    print '</br>'
    # 收件人
    print 'To:', email.utils.parseaddr(message.get('to'))[1]
    print '</br>'
    # 抄送人
    print 'Cc:',email.utils.parseaddr(message.get_all('cc'))[1]
    print '--------',message.get_all('Received')
    print type(message.get('Date')),message.get('Date')

def selectMail(message):
    pass



def parseBody(message):
    """ 解析邮件/信体 """
    # 循环信件中的每一个mime的数据块
    for part in message.walk():
        # 这里要判断是否是multipart，是的话，里面的数据是一个message 列表
        if not part.is_multipart():
            charset = part.get_charset()
            # print 'charset: ', charset
            contenttype = part.get_content_type()
            # print 'content-type', contenttype
            name = part.get_param("name") #如果是附件，这里就会取出附件的文件名
            if name:
                # 有附件
                # 下面的三行代码只是为了解码象=?gbk?Q?=CF=E0=C6=AC.rar?=这样的文件名
                fh = email.Header.Header(name)
                fdh = email.Header.decode_header(fh)
                subject = message.get('subject')
                h = email.Header.Header(subject)
                dh = email.Header.decode_header(h)
                fname = dh[0][0]
                print '附件名:', fname
                attach_data = part.get_payload(decode=True) #　解码出附件数据，然后存储到文件中

                try:
                    f = open(yesterday+'HOS'+'.xlsx', 'wb') #注意一定要用wb来打开文件，因为附件一般都是二进制文件
                except:
                    print '附件名有非法字符，自动换一个'
                    f = open('aaaa', 'wb')
                f.write(attach_data)
                f.close()
            else:
                #不是附件，是文本内容
                # print part.get_payload(decode=True) # 解码出文本内容，直接输出来就可以了。
                pass
            # print '+'*60 # 用来区别各个部分的输出

def is_todaydata(message,datestr):
    datstr1=message.get('Date')
    from_mail=email.utils.parseaddr(message.get('from'))[1]
    print 'datestr:',datestr,type(datestr),'datestr1:',datstr1,type(datstr1),'from:',from_mail,type('from'),'if:',datestr in datstr1 and '2541692705@qq.com' in from_mail
    if datestr in datstr1 and '2541692705@qq.com' in from_mail:
        return True
    else:
        return False

def getMail(host, username, password,datestr, port=993):
    try:
        serv = imaplib.IMAP4_SSL(host, port)
    except Exception, e:
        serv = imaplib.IMAP4(host, port)
    # print username,passwd
    serv.login(username, password)

    serv.select()
    # 搜索邮件内容
    # typ, data = serv.search(None, '(FROM "951730482@qq.com")')

    email_count = len(serv.search(None, '(FROM "951730482@qq.com")')[1][0].split())

    mail_index=email_count
    for i in range(0,10):
        typ, data = serv.fetch(str(mail_index-i), '(RFC822)')
        text = data[0][1]
        message = email.message_from_string(text)  # 转换为email.message对象
        if is_todaydata(message,datestr):
            print True
            break
        mail_index-=1

    # 选出今天邮箱
    typ, data = serv.fetch(str(mail_index), '(RFC822)')
    text = data[0][1]
    # print text
    # print '---------------'
    message = email.message_from_string(text)   # 转换为email.message对象
    if not is_todaydata(message, datestr):
        #pos没有接收到邮件
        pass
    # print message
    # print '--------------'
    # parseHeader(message)
    # print '</br>'
    # print '----------------------------------------------------'
    parseBody(message)
    serv.close()
    serv.logout()












def warn_mail(sendFrom,sendTo,passwd,logs):
    '''
    发送邮件的方法
    :param sendFrom: 发送人邮箱
    :param sendTo: 收件人邮箱
    :param passwd: 发送邮箱授权码
    :param msg: 发送信息
    :return:
    '''

    msgRoot = MIMEMultipart('related')
    msgText = MIMEText(logs, 'html', 'utf-8')
    msgRoot.attach(msgText)

    msgRoot['From'] = formataddr(["marvin", sendFrom])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
    msgRoot['To'] = formataddr(["邮箱警告提醒", sendTo])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
    msgRoot['Subject'] = "数据任务执行检查"  # 邮件的主题，也可以说是标题
    server = smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器，端口是465
    server.login(sendFrom, passwd)  # 括号中对应的是发件人邮箱账号、邮箱密码
    server.sendmail(sendFrom, [sendTo], msgRoot.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
    server.quit()  # 这句是关闭连接的意思


if __name__ == '__main__':
    sendFrom = '2541692705@qq.com'  #
    # passwd = "kpxlnuazfpowebch"  # 授权码
    passwd = "lnlqkdwmwujldihg"  # 授权码
    # 输入邮件地址, 口令和POP3服务器地址:端口995
    # email2 = '2541692705@qq.com'
    # password = "kpxlnuazfpowebch"
    # pop3_server = 'pop.qq.com'
    week_month=(datetime.datetime.now()+datetime.timedelta(days=0, hours=-0.5)).ctime()[0:7]
    # Sun Feb 2019-02-24 12:41:59.397000
    # print week_month,datetime.datetime.now()+datetime.timedelta(days=0, hours=-0.5)
    # print week_month[0:3],'------',week_month[4:7]
    datestr=week_month[0:3]+', '+str(datetime.datetime.now().day)+' '+week_month[4:7]+' '+str(datetime.datetime.now().year)
    print datestr
    getMail('imap.qq.com',sendFrom,passwd,datestr)
